<template>
  <div>
    <!-- 头部 -->
    <div class="address-top">
      <p @click="back">取消</p>
      <p>个人设置</p>
      <p @click="save">提交</p>
    </div>
    <!-- 头部 end -->
    <!-- 列表 -->
    <div class="white">
      <div class="flex user-list user" @click="change(0)">
        <img class="icon" :onerror="defaultImg" :src="userMes.Tag_Profile_IM_Image?userMes.Tag_Profile_IM_Image:defaultHead">
        <div class="flex right">
          <p>更换头像</p>
          <img src="../../assets/img/addressList/arrow-right.png">
        </div>
      </div>
      
      <div class="flex user-list">
        <p>账号</p>
        <div class="flex right">
          <p>{{userMes.To_Account}}</p>
        </div>
      </div>
      <div class="flex user-list">
        <p>昵称</p>
        <div class="flex right">
          <input type="text" class="nickName" v-model="nickName" placeholder="未填写">
          <img src="../../assets/img/addressList/arrow-right.png">
        </div>
      </div>
      <div class="flex user-list last" @click="change(1)">
        <p>性别</p>
        <div class="flex right">
          <p>{{sex[userMes.Tag_Profile_IM_Gender]}}</p>
          <img src="../../assets/img/addressList/arrow-right.png">
        </div>
      </div>
    </div>
    <div class="blank"></div>
    <div class="white">
      <div class="flex user-list last" @click="change(2)">
        <p>加好友设置</p>
        <div class="flex right">
          <p>{{option[userMes.Tag_Profile_IM_AllowType]}}</p>
          <img src="../../assets/img/addressList/arrow-right.png">
        </div>
      </div>
    </div>
    <!-- 底部菜单 -->
    <mt-actionsheet :actions="actions[index]" v-model="sheetVisible"></mt-actionsheet>
    <!-- 文件上传-->
    <form id="uploadForm" ref="uploadForm">
      <input type="file" @change="changeFile" ref="uploadFileId">
    </form>
  </div>
</template>
<style lang="less" rel="stylesheet/less" scoped>
.placeholder(@rules) {
    &::-webkit-input-placeholder {
        @rules();
    }
}
  .nickName {
    color: #818181;
    text-align: right;
    font-size:.12rem;
    .placeholder({
			color: #818181;
		});
  }

  #uploadForm {
    display: none;
  }

  .user-list {
    align-items: center;
    justify-content: space-between;
    height: .5rem;
    margin: 0 .15rem;
    border-bottom: .005rem solid #E9E9E9;
    &.last {
      border-bottom: 0;
    }
    p {
      color: #414141;
      font-size:.14rem;
    }
    .right {
      align-items: center;
      img {
        width: .15rem;
      }
      p {
        color: #818181;
        font-size:.12rem
      }
    }
  }

  .user {
    height: .8rem;
    .icon {
      width: .5rem;
      height: .5rem;
      border-radius: 50%;
    }
  }

</style>
<script>
  import Client from '../../assets/js/common';
  import CosCloud from '../../../static/cos-js-sdk-v4';
  import {axiosPost} from '../../assets/api';
  import {checkStatus} from '../../assets/js/login';
  import {Toast, Indicator} from 'mint-ui';
  import defaultHead from '../../assets/img/my@3x.png';
  export default {
    data () {
      return {
        nickName: undefined,
        userMes: {},   // 用户信息
        actions: [
          [{name: '相册', method: this.takePhoto}],
          [{name: '男', method: this.selectSex, type: 'Gender_Type_Male'},
            {name: '女', method: this.selectSex, type: 'Gender_Type_Female'}],
          [{name: '需要确认', type: 'AllowType_Type_NeedConfirm', method: this.selectSure},
            {name: '允许任何人', type: 'AllowType_Type_AllowAny', method: this.selectSure},
            {name: '拒绝任何人', type: 'AllowType_Type_DenyAny', method: this.selectSure}
          ]
        ],
        index: 0,  // 0 相册  1 性别   2 加好友设置
        sheetVisible: false,
        cosdata: '',
        cos: '',
        loginInfo: {},
        sex: {
          'Gender_Type_Male': '男',
          'Gender_Type_Female': '女',  // 腾讯字段
          'Gender_Type_Unknown':'未知'
        },
        option: {
          'AllowType_Type_NeedConfirm': '需要确认',
          'AllowType_Type_AllowAny': '允许任何人',
          'AllowType_Type_DenyAny': '拒绝任何人'
        },
        isSet: false,  // 是否有修改数据
        defaultHead,
        defaultImg:Client.defaultImg
      }
    },
    mounted () {
      checkStatus((loginInfo) => {
        this.loginInfo = loginInfo;
        this.getProfile([this.loginInfo.identifier]); // 获取用户资料
      });
    },
    methods: {
      // 返回
      back(){
        history.back()
      },
      // 提交
      save(){
        if(this.nickName != this.oriName){
          this.isSet = true;
        }
        if (!this.isSet) {
          Toast('您还没修改过资料');
          return
        }
        if(!this.nickName){
          Toast('请填写您的昵称');
          return;
        }
        if(this.nickName&&!this.nickName.trim()){
          Toast('昵称不能为空');
          return;
        }
        if(this.nickName&&this.nickName.length>8){
          Toast('昵称不能超过8个汉字');
          return;
        }
        let profile_item = [
          {
            "Tag": "Tag_Profile_IM_Nick",
            "Value": this.nickName
          },
          {
            "Tag": "Tag_Profile_IM_Gender",
            "Value": this.userMes.Tag_Profile_IM_Gender
          },
          {
            "Tag": "Tag_Profile_IM_AllowType",
            "Value": this.userMes.Tag_Profile_IM_AllowType
          },
          {
            "Tag": "Tag_Profile_IM_Image",
            "Value": this.userMes.Tag_Profile_IM_Image
          }
        ];
        profile_item.forEach((ele, i)=>{
          if(ele.Tag == 'Tag_Profile_IM_Gender' && ele.Value == 'Gender_Type_Unknown'){
            profile_item.splice(i,1);
          }
          if(ele.Tag == 'Tag_Profile_IM_Image' && !ele.Value){
            profile_item.splice(i,1);
          }
          if(ele.Tag == 'Tag_Profile_IM_Nick' && !ele.Value){
            profile_item.splice(i,1);
          }
        });
        let options = {
          'ProfileItem': profile_item
        };
        webim.setProfilePortrait(
          options,
          resp => {
            Toast('设置个人资料成功');
            setTimeout(()=>{
              this.loginInfo.onProfileModifyNotify = null;
              this.back();
            }, 500);
          },
          err => {
            Client.errInfo();
            console.log(err.ErrorInfo);
          }
        );
      },
      // 底部菜单
      change(index){
        this.sheetVisible = true;
        this.index = index;
      },
      // 拍照
      takePhoto(){
        this.$refs.uploadFileId.click();
      },
      // 性别
      selectSex(val){
        this.isSet = true;
        this.userMes.Tag_Profile_IM_Gender = val.type;
      },
      // 加好友设置
      selectSure(val){
        this.isSet = true;
        this.userMes.Tag_Profile_IM_AllowType = val.type;
      },
      // 上传头像
      changeFile(e){
        let _this = this;
        let apiname = "upload/uploadHeadPic";
        let reader = new FileReader(),
            getfile = e.srcElement.files[0];
        reader.onload = (getfile => {
          return e => {
            this.userMes.Tag_Profile_IM_Image = e.srcElement.result;
          };
        })(getfile);
        reader.readAsDataURL(getfile);
        axiosPost({
          data: {
            "fileEtension": "jpg",
            "signType": 0
          },
          url: apiname + '?token=123&appSecret=8888',
          onSuccess (res) {
            _this.cosdata = res.data.Result;
            _this.cos = new CosCloud({
              appid: _this.cosdata.appid, // APPID 必填参数
              bucket: _this.cosdata.bucket, // bucketName 必填参数
              region: _this.cosdata.region, // 地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
              getAppSign: function (callback) {
                callback(_this.cosdata.AppSign);
              },//多次签名 可使用多次
              getAppSignOnce: function (callback) {

                callback(_this.cosdata.AppSignOnce);
              }
            });
            _this.uploadFile(e)
          },
          onFailure (res) {
            Client.errInfo();
          }
        })
      },
      // 文件上传
      uploadFile(e){
        let _this = this
        // let myFolder = 'head/';//需要操作的目录

        let successCallBack = function (result) {
          Indicator.close();
          if(result.code !== 0){
            Toast('图片上传失败');
            return;
          }else{
            _this.userMes.Tag_Profile_IM_Image = result.data.access_url;
            _this.isSet = true;
            Toast('图片上传成功');
          }
        };

        let errorCallBack = function (result) {
          Indicator.close();
          result = result || {};
          console.log('request error:', result && result.message);
        };


        let progressCallBack = function (curr, sha1) {
          /*let sha1CheckProgress = ((sha1 * 100).toFixed(2) || 100) + '%';
          let uploadProgress = ((curr || 0) * 100).toFixed(2) + '%';
          let msg = 'upload progress:' + uploadProgress + '; sha1 check:' + sha1CheckProgress + '.';
          if (uploadProgress == '100.00%') {
            Indicator.close();
            Toast('图片上传成功')
            _this.isSet = true
          }*/
        };
        let lastTaskId;
        let taskReady = function (taskId) {
          lastTaskId = taskId;
        };
        let file = e.target.files[0];
        let fileLimit = 1024 * 1024 * 20;  // 1M图片限制
        if (!file.type.includes('image')) {
          Toast("请上传图片格式的文件")
          this.$refs.uploadForm.reset()
          return false
        }
        if (file.size > fileLimit) {
          Toast('请上传20M以内的图片')
          this.$refs.uploadForm.reset()
          return false
        }
        // 分片上传过程可能会有 op=upload_slice_list 的 POST 请求返回 404，不会影响上传
        Indicator.open();
        this.cos.uploadFile(successCallBack, errorCallBack, progressCallBack, this.cosdata.bucket,
          this.cosdata.fileName, file, 0, taskReady);//insertOnly==0 表示允许覆盖文件 1表示不允许
        return false;
      },
      // 获取用户资料
      getProfile(arr) {
        let tag_list = [
          "Tag_Profile_IM_Nick", //昵称
          "Tag_Profile_IM_Gender", //性别
          "Tag_Profile_IM_AllowType", //加好友方式
          "Tag_Profile_IM_Image" //头像
        ];
        let objs = {
          To_Account: arr,
          TagList: tag_list
        };
        webim.getProfilePortrait(
          objs,
          resp => {
            if (resp.UserProfileItem && resp.UserProfileItem.length > 0) {
              for (let i = 0; i < resp.UserProfileItem.length; i++) {
                if (resp.UserProfileItem[i].ProfileItem) {
                  let sonItem = resp.UserProfileItem[i].ProfileItem;
                  sonItem.forEach((ele, index) => {
                    resp.UserProfileItem[i][ele.Tag] = ele.Value;
                  });
                  delete resp.UserProfileItem[i].ProfileItem  // 删除属性
                }
              }
              this.userMes = resp.UserProfileItem[0];
              if(!this.userMes.Tag_Profile_IM_Gender){
                this.userMes.Tag_Profile_IM_Gender = 'Gender_Type_Unknown';
              }
              if(!this.userMes.Tag_Profile_IM_AllowType){
                this.userMes.Tag_Profile_IM_AllowType = 'AllowType_Type_AllowAny';
              }
              if(this.userMes.Tag_Profile_IM_Nick){
                this.nickName = this.oriName = this.userMes.Tag_Profile_IM_Nick;
              }
            }
          },
          err => {
            Client.errInfo();
            console.log(err.ErrorInfo);
          }
        );
      },

    },
    watch:{
      'loginInfo.onProfileModifyNotify':function(val){
        //资料变化
        if(val == null || val == {}){
            return
        }else if(val.image){
          this.loginInfo.headurl = val.image;
        }
      }
    }
  }

</script>
